// CyTargetLinker,
// a Cytoscape plugin to extend biological networks with regulatory interaction
// Copyright 2011-2012 BiGCaT Bioinformatics
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package cytargetlinker.dialogs;

import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;

import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

import cytargetlinker.CyTargetLinker;
import cytargetlinker.CyTargetLinker.Direction;
import cytoscape.CyNetwork;
import cytoscape.Cytoscape;

/**
 * dialog to load the regulatory interaction networks
 * network attribute = attribute containing a biological identifier in teh user network
 * RIN directory = directory that contains one or more RIN files
 */
public class CyTargetLinkerDialog extends JDialog {
	
	private CyTargetLinker linker;
	private Map<String, File> rins;

	private JComboBox networkComboBox;
	private JTextField tfUserAttribute;
	private JTextField tfNetName;
	private JComboBox cbDirection;
	private JTextField dirField;
	
	private CellConstraints cc = new CellConstraints();

	public CyTargetLinkerDialog(CyTargetLinker linker) {
		super(Cytoscape.getDesktop());
		this.linker = linker;
		this.setLayout(new BorderLayout());
		this.add(getMainPanel());
		locate();
		this.setResizable(false);
		this.pack();
	}

	private void locate() {
		int sizeX = 300;
		int sizeY = 300;
		this.setSize(sizeX, sizeY);

		Point cyLocation = Cytoscape.getDesktop().getLocation();
		int cyHeight = Cytoscape.getDesktop().getHeight();
		int cyWidth = Cytoscape.getDesktop().getWidth();

		Point middle = new Point(cyLocation.x + (cyWidth / 2), cyLocation.y + (cyHeight / 2));

		int locX = middle.x - (sizeX / 2);
		int locY = middle.y - (sizeY / 2);
		this.setLocation(new Point(locX, locY));
	}

	private JPanel getMainPanel() {
		FormLayout layout = new FormLayout("p", "p, 3dlu, p, 3dlu, p, 3dlu, p");
		PanelBuilder builder = new PanelBuilder(layout);
		builder.setDefaultDialogBorder();
		builder.add(getUserPanel(), cc.xy(1, 1));
		builder.add(getTargetPanel(), cc.xy(1, 3));
		builder.add(getSettings(), cc.xy(1,5));
		builder.add(getCancelOkPanel(), cc.xy(1, 7));
		return builder.getPanel();
	}

	private JPanel getSettings() {
		FormLayout layout = new FormLayout("right:max(72dlu;p), 10dlu, 75dlu, 10dlu", "5dlu, p, 5dlu, p , 5dlu");
		PanelBuilder builder = new PanelBuilder(layout);
		builder.setDefaultDialogBorder();
		builder.setBorder(new TitledBorder("Settings"));
		builder.addLabel("Resulting Network name", cc.xy(1, 2));

		tfNetName = new JTextField();
		tfNetName.setText("CTL_" + networkComboBox.getSelectedItem());
		tfNetName.setEditable(true);
		builder.add(tfNetName,cc.xy(3, 2));
		
		Vector<Direction> vec = new Vector<Direction>();
		vec.add(Direction.BOTH);
		vec.add(Direction.SOURCE);
		vec.add(Direction.TARGET);
		cbDirection = new JComboBox(vec);
		cbDirection.setSelectedIndex(0);
		
		builder.add(new JLabel("Select direction"), cc.xy(1, 4));
		builder.add(cbDirection, cc.xy(3, 4));
		return builder.getPanel();
	}

	private JPanel getTargetPanel() {
		FormLayout layout = new FormLayout("right:max(72dlu;p), 10dlu, 75dlu, 5dlu, p, 10dlu", "5dlu, p, 10dlu");
		PanelBuilder builder = new PanelBuilder(layout);
		builder.setDefaultDialogBorder();
		builder.setBorder(new TitledBorder("Directory containg regulatory interaction networks"));
		builder.addLabel("Select RINs", cc.xy(1, 2));

		dirField = new JTextField();
		if(linker.getPlugin().getNetworkDirectory() != null) {
			dirField.setText(linker.getPlugin().getNetworkDirectory().getAbsolutePath());
			getRINFiles();
		}
		dirField.setEditable(false);
		builder.add(dirField,cc.xy(3, 2));
		
		
		JButton browseButton = new JButton("Browse");
		browseButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				JFileChooser chooser = new JFileChooser();
				Cytoscape.getDesktop();
			    chooser.setDialogTitle("Select directory containing RINs");
			    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
			    	File dir = chooser.getSelectedFile();
			    	linker.getPlugin().setNetworkDirectory(dir);
			    	dirField.setText(dir.getAbsolutePath());
			    	getRINFiles();
			    }
			}
		});
		builder.add(browseButton, cc.xy(5, 2));
		
		return builder.getPanel();
	}

	private JPanel getUserPanel() {
		FormLayout layout = new FormLayout("right:max(72dlu;p), 10dlu, 75dlu, 10dlu", "5dlu, p, 5dlu, p, 5dlu, p, 15dlu");
		PanelBuilder builder = new PanelBuilder(layout);
		builder.setDefaultDialogBorder();
		builder.setBorder(new TitledBorder("User Network"));
		
		builder.addLabel("Select User Network", cc.xy(1, 2));
		networkComboBox = new JComboBox(getNetworks());
		networkComboBox.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				tfNetName.setText("CTL_" + networkComboBox.getSelectedItem());
			}
		});
		builder.add(networkComboBox, cc.xy(3, 2));
		
		builder.addLabel("Select your network attribute", cc.xy(1, 4));
		tfUserAttribute = new JTextField();
		builder.add(tfUserAttribute, cc.xy(3, 4));
		
		return builder.getPanel();
	}

	private JPanel getCancelOkPanel() {
		FormLayout layout = new FormLayout("right:max(72dlu;p), 10dlu, 72dlu, 10dlu", "5dlu, p, 5dlu");
		PanelBuilder builder = new PanelBuilder(layout);
		builder.setDefaultDialogBorder();
		JButton button1 = new JButton("Cancel");
		button1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
					dispose();
			}
		});
		builder.add(button1, cc.xy(1, 2));
		JButton button2 = new JButton("Ok");
		button2.addActionListener(new ActionListener(){
			public void  actionPerformed(ActionEvent e) {

				if(!tfUserAttribute.getText().equals("")) {
					Object userNetTitle = networkComboBox.getSelectedItem();
					CyNetwork userNet = userNetworks.get(userNetTitle);
					String selectedAttribute = tfUserAttribute.getText();
					linker.setUserNetwork(userNet, selectedAttribute);
					
					//Warning if there is no xgmml files is the directory selected 
					if (rins.isEmpty()|| rins == null) {
						JOptionPane.showMessageDialog(Cytoscape.getDesktop(), "No xgmml file in this Directory.", "Warning", JOptionPane.WARNING_MESSAGE);
					} else {
						if(tfNetName.getText().equals("")) {
							linker.setResNetName("CTL_" + networkComboBox.getSelectedItem());
						} else {
							linker.setResNetName(tfNetName.getText());
						}
						setDirection();
						dispose();
						RINSelectionDialog dlg = new RINSelectionDialog(linker, rins);
						dlg.setVisible(true);
					}
				} else {
					if (tfUserAttribute.getText().equals("")){
						JOptionPane.showMessageDialog(Cytoscape.getDesktop(), "No network attribute.", "Warning", JOptionPane.WARNING_MESSAGE);
						
					}
				}
			}

			private void setDirection() {
				if(cbDirection.getSelectedItem().equals(Direction.SOURCE)) {
					linker.setDirection(Direction.SOURCE);
				} else if (cbDirection.getSelectedItem().equals(Direction.TARGET)) {
					linker.setDirection(Direction.TARGET);
				} else {
					linker.setDirection(Direction.BOTH);
				}
			}	
		});
		builder.add(button2, cc.xy(3, 2));
		return builder.getPanel();
	}

	private Map<String, CyNetwork> userNetworks;

	private Vector<String> getNetworks() {
		userNetworks = new HashMap<String, CyNetwork>();
		Set<CyNetwork> networks = Cytoscape.getNetworkSet();
		Vector<String> vec = new Vector<String>();

		for (CyNetwork net : networks) {
			userNetworks.put(net.getTitle(), net);
			vec.add(net.getTitle());
		}
		return vec;
	}

	private void getRINFiles() {
		rins = new HashMap<String, File>();
		File file = new File(dirField.getText());
		if (file != null){
			File[] files = file.listFiles();
			
			for (int i = 0; i < files.length; i++) {
				if (files[i].isFile() && files[i].getName().contains(".xgmml")) {
					//we only take the first ten available network files
					if( rins.size()<=10){
						rins.put(files[i].getAbsolutePath(), files[i]);
					}
				}
			}
		}
	}
	


}

